# coding- utf-8

# 线程锁多线程实例

import random
import threading
import time

# 创建锁
gLock = threading.Lock()

# 创建全局变量MONEY
MONEY = 0

def Producer():
    while True:
        global MONEY
        random_money = random.randint(10,100)
        gLock.acquire()
        MONEY +=random_money
        print('生产者%s生产了%s \n' % (threading.current_thread(), random_money))
        gLock.release()
        time.sleep(0.5)

def Customer():
    while True:
        global MONEY
        random_money = random.randint(10,100)
        if MONEY > random_money:
            gLock.acquire()
            MONEY -= random_money
            print('消费者%s消费了%s\n' % (threading.current_thread(), random_money))
            gLock.release()
        else:
            print("钱不够了\n")
        time.sleep(0.5)

def p_c_test():
    for x in range(3):
        th = threading.Thread(target=Producer)
        th.start()
    for x in range(3):
        th = threading.Thread(target=Customer)
        th.start()

if __name__ == "__main__":
    p_c_test()